package com.cygsunri.wisdompark.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.math.BigInteger;
import java.util.Base64;

public class Base64Util {


    /**
     * Base64解密成16进制
     *
     */
    public static String  decryptBASE64ToString(String key) throws Exception{
        byte[] byteArray = decryptBASE64(key);
        return BASE64ToString(byteArray);
    }

    /**
     * Base64
     *
     */
    public static void base64(String str) {
        byte[] bytes = str.getBytes();

        //Base64 加密
        String encoded = Base64.getEncoder().encodeToString(bytes);
        System.out.println("Base 64 加密后：" + encoded);

        //Base64 解密
        byte[] decoded = Base64.getDecoder().decode(encoded);

        String decodeStr = new String(decoded);
        System.out.println("Base 64 解密后：" + decodeStr);

        System.out.println();


    }

    /**
     * BASE64加密解密
     */
    public static void enAndDeCode(String str) throws Exception {
        String data = encryptBASE64(str.getBytes());
        System.out.println("sun.misc.BASE64 加密后：" + data);
        byte[] byteArray = decryptBASE64(data);
        System.out.println("sun.misc.BASE64 解密后：" + new String(byteArray));
    }

    /**
     * BASE64解密
     * @throws Exception
     */
    public static byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }

    /**
     * BASE64加密
     */
    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }


    /**
     * 字节转16进制字符串
     * @throws Exception
     */
    public static String BASE64ToString(byte[] byteArray) throws Exception {
        String result = new String();
        for (int i = 0; i < byteArray.length; i++)
        {
            String hex = Integer.toHexString(byteArray[i] & 0xFF);
            if (hex.length() == 1)
            {
                hex = '0' + hex;
            }
            result +=hex.toUpperCase();
        }
        return result;
    }


    /**
     * 16进制转10进制
     * @throws Exception
     */
    public static int hex16To10(String strHex){
        BigInteger ingNum = new BigInteger(strHex,16);
        return  ingNum.intValue();
    }


}
